#-------------------------------------------------------------------------------
# Name:        ControlWidget
# Purpose:
#
# Author:      Pablo
#
# Created:     21/08/2013
# Copyright:   (c) Monxcleyr Productions 2013
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import pygame, os
from ..gui import label

class ControlWidget():

  """class comment"""

  def __init__(self, surface, soundsystem, settings, pos, name, clicksound, hoversound, control, current, default, font, fontcolor, graphics):
    self.surface = surface
    self.soundsystem = soundsystem
    self.settings = settings
    self.pos = pos
    self.name = name
    self.clicksound = clicksound
    self.hoversound = hoversound
    self.control = control
    self.current = current
    self.default = default
    self.font = font
    self.fontcolor = fontcolor
    self.graphics = [pygame.image.load(os.path.join('resources/graphics/' + graphics[0])).convert_alpha(), \
      pygame.image.load(os.path.join('resources/graphics/' + graphics[1])).convert_alpha(),\
      pygame.image.load(os.path.join('resources/graphics/' + graphics[2])).convert_alpha()]

    self.namelabel = label.Label(surface, self.name, (self.pos[0] - 2, self.pos[1] + 2), 'right', self.font, self.fontcolor)
    self.keylabel = label.Label(surface, ' ', (self.pos[0] + (self.graphics[0].get_width()/2), self.pos[1] + 2), 'center', self.font, self.fontcolor)
    self.rect =  self.graphics[0].get_rect()
    self.rect.topleft = self.pos
    # Holds if the widgets is currently checking for a keypress, if it is, options.py will hide the mouse
    # and forbid mouse input until a key has been pressed.
    self.checking = False
    self.prevhover = False

  def draw(self, mouse):

    self.namelabel.draw()

    self.surface.blit(self.graphics[0], self.pos)

    if self.rect.collidepoint(mouse[0]):
      self.surface.blit(self.graphics[1], self.pos)
      if self.prevhover == False:
        self.soundsystem.play(self.hoversound, self.settings)
        self.prevhover = True
      if mouse[1]:
        self.soundsystem.play(self.clicksound, self.settings)
        self.checking = True
    else:
      self.prevhover = False

    if self.checking:
      key = None
      self.surface.blit(self.graphics[2], self.pos)
      self.keylabel.setText(' ')
      pressed = pygame.key.get_pressed()
      if pressed.count(1) > 0:
        key = pressed.index(1)
        if key in [301,302,300]:
          key = None

      if key:
        self.current = key
        self.soundsystem.play(self.clicksound, self.settings)
        self.checking = False


    else:
      self.keylabel.setText(pygame.key.name(self.current).upper())

    self.keylabel.draw()